<?php
/**
 * AdminController for managing admins user
 *
 * @author fusq
 */
require_once BaseUtil::getModulePath("base")  .  '/controllers/BaseController.php';
require_once BaseUtil::getModulePath('dbgrid') . '/DBGrid.php';
require_once BaseUtil::getModulePath("acl")  .  '/services/AdminService.php';
require_once BaseUtil::getModulePath("acl")  .  '/services/AAService.php';
require_once BaseUtil::getModulePath("acl")  .  '/forms/AdminForm.php';
require_once BaseUtil::getModulePath("acl")  .  '/forms/AdminEditForm.php';
require_once BaseUtil::getModulePath("acl")  .  '/forms/LoginForm.php';
require_once BaseUtil::getModulePath("acl")  .  '/forms/MyAccountEditForm.php';
require_once BaseUtil::getModulePath('acl') . '/constants/Permission.php';

class Acl_AdminController  extends BaseController {

    public function init(){
        parent::init();
        parent::addLocaleData("acl");
	}

    public function indexAction(){
    	$dbgrid = new DBGrid($this->view);
        $dbgrid->setPost($_POST);
        $dbgrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT, "admins-username", $this->_translate->translate("userName"));
        $dbgrid->addOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "admins-status", $this->_translate->translate("userStatus"),array("1"=>$this->_translate->translate("statusA"),"0"=>$this->_translate->translate("statusI")));
        $dbgrid->addFetchTable("admins", array('id' , 'username' , 'email','status','created'));
        $dbgrid->addValueFilter('admins-is_delete', '0');
        $dbgrid->addFetchColumn("username", $this->_translate->translate("userName"),"edit");
        $dbgrid->addFetchColumn("email", $this->_translate->translate("userEmail"));
        $dbgrid->addFetchColumn("status", $this->_translate->translate("userStatus"),"",array("1"=>$this->_translate->translate("statusA"),"0"=>$this->_translate->translate("statusI")));
        $dbgrid->addFetchColumn("created", $this->_translate->translate("createDate"));
        $dbgrid->setModule('/acl/admin');
        if(AAService::isAllowed("admin", "edit")){
            $dbgrid->addAAModuleAction("admin", "edit",$this->_translate->translate("editBtn"),"edit");
        }
        if(AAService::isAllowed("admin", "deletesome")){
            $dbgrid->addAAModuleAction("admin", "delete",$this->_translate->translate("delBtn"),"deletesome");
        }
        if(AAService::isAllowed("admin", "add")){
            $dbgrid->addAAModuleAction("admin", "add",$this->_translate->translate("addBtn"),"add");
        }
        $dbgrid->setPageTitle($this->_translate->translate("manageAdminTitle"));
        $this->view->dbGrid = $dbgrid->render();
    }

    public function addAction(){

        $adminService = new AdminService();
        $departments = $adminService->getDepartments();
        $roles = $adminService->getRoles();
        $adminForm = new AdminForm($departments[1],$roles);
        $this->view->departments = $departments[0];
        $this->view->form = $adminForm;
    }

    public function subaddAction(){
        $adminService = new AdminService();
        $departments = $adminService->getDepartments();
        $roles = $adminService->getRoles();
        $adminForm = new AdminForm($departments[1],$roles);
		if (!$adminForm->isValid($_POST)) {
			$this->view->form = $adminForm;
            $this->view->departments = $departments[0];
            return $this->render('add');
		}
        $admin = array();
        $admin['username'] = $adminForm->getValue("name");
        $admin['password'] = md5($adminForm->getValue("password"));
        $admin['email'] = $adminForm->getValue("email");
        $departments = $adminForm->getValue("department");
        $role = $adminForm->getValue("role");
        $adminService->addAdmin($admin, $role, $departments);
        $this->_redirector->gotoUrl('acl/admin');
    }

   public function editAction(){
        $adminId = $this->_getParam('id');
        $adminService = new AdminService();
        $admin = $adminService->getAdminById($adminId);
        $departments = $adminService->getDepartments();
        $adminDepartments = $adminService->getDepartmentsByAdmin($adminId);
        $permissions = Permission::getAllPermissions();
        $adminPermissions = $adminService->getPermissionsByAdmin($adminId);
        $adminForm = new AdminEditForm($departments[1],$permissions,$admin,$adminDepartments,$adminPermissions);
        //$roles = $adminService->getRoles();
        //$adminForm = new AdminForm($departments[1],$roles);
        $this->view->departments = $departments[0];
        $this->view->permissions = $permissions;
        $this->view->form = $adminForm;
        $this->view->id=$adminId;
   }

   public function subeditAction(){
        $adminService = new AdminService();
        $departments = $adminService->getDepartments();
        $permissions = Permission::getAllPermissions();
        $adminId = HttpUtil::getPostString("adminId");
        $admin = array("id" => $adminId);
        $adminForm = new AdminEditForm($departments[1],$permissions,$admin);
		if (!$adminForm->isValid($_POST)) {
			$this->view->form = $adminForm;
            $this->view->departments = $departments[0];
            $this->view->permissions = $permissions;
            return $this->render('edit');
		}
        //Init data to save
        $admin = array();
        $name = $adminForm->getValue("name");
        $email = $adminForm->getValue("email");
        $status = $adminForm->getValue("status");
        $password = $adminForm->getValue("password");
        $adminDepartments = $adminForm->getValue("department");
        $adminPermissions = $adminForm->getValue("permission");
        $adminId = $adminForm->getValue("adminId");
        $admin["username"] = $name;
        $admin["email"] = $email;
        $admin["status"] = $status;
        if(!empty($password)){
            $admin['password'] = md5($password);
        }
        $adminService->updateAdmin($adminId,$admin, $adminDepartments, $adminPermissions);
        $this->_redirector->gotoUrl('acl/admin');
   }

   public function deletesomeAction(){
        $idsStr = HttpUtil::getPostValue("selectIds");
        $ids = explode(",",$idsStr);
		$adminService = new AdminService();
		$adminService->deleteAdmins($ids);
		$this->_redirector->gotoUrl('acl/admin');
    }
    
    public function loginAction(){
        $this->_helper->layout->disableLayout();
        $loginForm = new LoginForm();
        $this->view->form = $loginForm;
    }

    public function subloginAction(){
        $this->_helper->layout->disableLayout();
        $loginForm = new LoginForm();
        if (!$loginForm->isValid($_POST)) {
            $loginForm->setErrorMessages(array($this->_translate->translate("loginError")));
			$this->view->form = $loginForm;
            //for Captcha
            if(!isset($_SESSION['loginFailedTime']) || empty($_SESSION['loginFailedTime'])){
                 $_SESSION['loginFailedTime'] = 1;
            }else{
                 $_SESSION['loginFailedTime'] += 1;
            }
            return $this->render('login');
		}
        //check Captcha
        $confirmCode = isset($_POST["confirmCode"]) ? $_POST["confirmCode"] : null ;
        if(isset($confirmCode)){
            $captchaCode = $_SESSION['captcha']['code'];
            if(strtolower($confirmCode) != strtolower($captchaCode)){
                $loginForm->setErrorMessages(array($this->_translate->translate("captchaError")));
                $this->view->form = $loginForm;
                //for Captcha
                if(!isset($_SESSION['loginFailedTime']) || empty($_SESSION['loginFailedTime'])){
                     $_SESSION['loginFailedTime'] = 1;
                }else{
                     $_SESSION['loginFailedTime'] += 1;
                }
                return $this->render('login');
            }
        }
        
        $email = $loginForm->getValue("email");
        $password = $loginForm->getValue("password");
        $adminService = new AdminService();
        $result = $adminService->login($email, $password);
        if(!empty($result)){
            //put user obj in to session
            $_SESSION['loginUser'] = $result;
            //put acl abj in to zend registry
            $aaService = new AAService();
            $aaService->initUserPermissions($result['uid']);
            unset($_SESSION['loginFailedTime']);
            $this->_redirector->gotoUrl("acl/admin");
        }else{
            $loginForm->setErrorMessages(array($this->_translate->translate("loginError")));
			$this->view->form = $loginForm;
            //for Captcha
            if(!isset($_SESSION['loginFailedTime']) || empty($_SESSION['loginFailedTime'])){
                 $_SESSION['loginFailedTime'] = 1;
            }else{
                 $_SESSION['loginFailedTime'] += 1;
            }
            return $this->render('login');
        }        
    }

    public function logoutAction(){
        BaseUtil::clearSession();
        $this->_redirector->gotoUrl("acl/admin/login");
    }

    public function editinfoAction(){
        $user = BaseUtil::getLoginUser();
        $userid = $user['uid'];
        $adminService = new AdminService();
        $admin = $adminService->getAdminById($userid);
        $form = new MyAccountEditForm($admin);
        $this->view->form = $form;
    }

    public function subeditinfoAction(){
        $user = BaseUtil::getLoginUser();
        $userid = $user['uid'];
        $admin = array("id" => $userid);
        $form = new MyAccountEditForm($admin);
        if (!$form->isValid($_POST)) {
			$this->view->form = $form;
            return $this->render('editinfo');
		}
        $name = $form->getValue("name");
        $email = $form->getValue("email");
        $password = $form->getValue("password");
        $admin = array();
        $admin["username"] = $name;
        $admin["email"] = $email;
        if(!empty($password)){
            $admin['password'] = md5($password);
        }
        $adminService = new AdminService();
        $adminService->updateAccount($userid,$admin);
        $this->_redirector->gotoUrl('/');
    }

    public function captchaAction(){

        header("Cache-Control: no-cache, must-revalidate");
        header("Content-type:image/PNG");
        $mypath = Zend_Registry::get("documentRoot");
        $fontface = $mypath . "/pub/images/captcha/arial.ttf";

        $str = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
        $code = "";
        for ($i = 0; $i < 6; $i ++) {
            $Xi = mt_rand(0, strlen($str) / 2);
            if ($Xi % 2)
                $Xi += 1;
            $code .= substr($str, $Xi, 1);
        }

        $im = imagecreatefrompng($mypath."/pub/images/captcha/yzpic.png");

        $bkcolor = null;
        imagefill($im, 0, 0, $bkcolor);
        for ($i = 0; $i < 6; $i ++) {
            $fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
            $codex = iconv("GB2312", "UTF-8", substr($code, $i * 2, 2));
            imagettftext($im, 12, mt_rand(- 15, 15), 26 * $i + 20, 20, $fontcolor, $fontface, $codex);
        }
        $a = rand(100000, 999999);
        $_SESSION['captcha'] = array();
        $_SESSION['captcha']['code'] = strtolower($code);
        imagepng($im);
        exit();
    }
    private function full_rmdir ($dir)
    {
        if (! is_writable($dir)) {
            if (! @chmod($dir, 0777)) {
                return false;
            }
        }
        $d = dir($dir);
        while (false !== ($entry = $d->read())) {
            if ($entry == '.' || $entry == '..') {
                continue;
            }
            $entry = $dir . '/' . $entry;
            if (is_dir($entry)) {
                if (! $this->full_rmdir($entry)) {
                    return false;
                }
                continue;
            }
            if (! @unlink($entry)) {
                $d->close();
                return false;
            }
        }
        $d->close();
        return true;
    }
    
    public function deleteAction() {
    	$id=$this->_getParam('id');
    	$adminService=new AdminService();
    	$adminService->delete($id);
    	$this->_redirector->gotoUrl('/acl/admin');
    }
}
